package tools

import (
	"fmt"
	"log"
	"prometheus_import_consul/global"
	"strconv"

	"github.com/hashicorp/consul/api"
)

func Add_Service(ip, service, ServiceType, portStr, env, businesscode string) {
	port, err := strconv.Atoi(portStr)
	if err != nil {
		log.Fatalf("Add_Service Error converting port to integer: %v\n", err)
		return
	}

	serviceID := service + "_" + portStr + "_" + ip
	serviceName := global.Config.Consul.ServiceName[3]

	// 创建服务注册的配置
	registration := &api.AgentServiceRegistration{
		ID:      serviceID,
		Name:    serviceName,
		Address: ip,
		Port:    port,
		Tags:    []string{global.Config.Consul.ServiceName[4]},
		Meta: map[string]string{
			"app_name":      service,
			"env":           env,
			"port":          portStr,
			"type":          ServiceType,
			"business_code": businesscode,
		},
		Check: &api.AgentServiceCheck{
			TCP:                            fmt.Sprintf("%s:%d", ip, port),
			Interval:                       "10s",
			Timeout:                        "20s",
			DeregisterCriticalServiceAfter: "5m", // 如果服务1分钟内处于critical状态，则自动注销
		},
	}

	// 使用global.ConsulClient注册服务
	if err := global.ConsulClient.Agent().ServiceRegister(registration); err != nil {
		log.Fatalf("Service Error registering service with Consul:%v\n", err)
		return
	}

	log.Printf("Service %s registered successfully\n", serviceID)
}
